package com.jacksen.demo.view.webview;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Button;

import com.jacksen.demo.view.R;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 测试与js互相调用方法
 *
 * @author ys
 */
public class TestAndroidAndJs extends AppCompatActivity {

    @Bind(R.id.callJsMethodBtn)
    Button callJsMethodBtn;
    @Bind(R.id.webView)
    WebView webView;

    private MyHandler handler = new MyHandler();


    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_android_and_js);
        ButterKnife.bind(this);

        //
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/test.html");

        webView.addJavascriptInterface(new DemoJavaScriptInterface(), "login");
//        webView.addJavascriptInterface(new JsObject(), "login");
//        webView.addJavascriptInterface(this, "login");
    }

    @OnClick(R.id.callJsMethodBtn)
    void loadUrl() {
        webView.loadUrl("javascript:updateHtml()");
    }


    class JsObject {
        @JavascriptInterface
        public String toString() {
            return "injectedObject";
        }
    }

    class DemoJavaScriptInterface {
        DemoJavaScriptInterface() {

        }

        public void clickOnAndroid() {
            handler.post(new Runnable() {
                public void run() {
                    handler.sendEmptyMessage(2);
                }
            });
        }
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    startFunction();
                    break;
                default:
                    break;
            }
        }
    }

    public void startFunction() {
        AlertDialog.Builder ab = new AlertDialog.Builder(this);
        ab.setTitle("提示");
        ab.setMessage("通过js 调用了 java 中的方法");
        ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        ab.create().show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
